package com.alipay.controller;

import com.alipay.model.ExceptionUtils;
import com.alipay.sofa.pay.facade.PayService;
import com.alipay.sofa.pay.facade.model.PayOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import com.alipay.model.ResponseBody;

import javax.ws.rs.QueryParam;


@RestController
public class OrderController {

    private final static Logger LOGGER = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private PayService payService;

    @GetMapping("/api/orders")
    public ResponseEntity<?> getOrders(@QueryParam("userId") String userId, @QueryParam("limit") Integer limit) {
        try{
            List<PayOrder> orders = payService.listPayOrders(userId, limit);
            ResponseBody body = new ResponseBody(orders);
            return ResponseEntity.ok(body);
        }catch (Exception e){
            return ResponseEntity.ok(new ResponseBody(500, "fail", "获取列表异常" + ExceptionUtils.getRootCause(e).getMessage()));
        }

    }

    @PostMapping("/api/orders")
    public ResponseEntity<?> pay(@RequestBody PayOrder order) {
        try {
            payService.pay(order.getBuyerId(), order.getSellerId(), order.getPayAmount());
            return ResponseEntity.ok(new ResponseBody("转账成功"));
        }catch (Exception e){
            LOGGER.error("转账异常", e);
            return ResponseEntity.ok(new ResponseBody(500, "fail", "转账异常 "+ ExceptionUtils.getRootCause(e).getMessage()));
        }

    }

}
